var appI =getApp()
var bgMusic = appI.globalData.bgMusic
var globalData = appI.globalData
Page({

  /*页面的初始数据*/
  data: {

    programs:[], //当前的播放列表的数据
    loading:1,  //是否显示等待动画
    uid:'', //当前的播放列表的信息
    tabid:'', //当前的tab类型
    triggered:true,  //设置下拉刷新关闭还是开启
    nowTitle:'', //当前的列表标题
    nowMusicId:'', //当前播放的歌曲信息
    bodanList:{},
    lishiJiLu:{},
    myBodan:{},
    ani:'',
    activeSwiperChange_list:2,
    zhezhaoHidden:'0',
    playListStatus:0,
    seacher_list_data:{programs:[]},
    seacher_list_displayVal:"1",
    seacher_ani:'',
    bodanNames:[{name:'请在【我的播单】中创建好播单在添加'}],
    addBoDanInfo:{},
  },
  
  //隐藏搜索列表
  onSeacherListHidden:function(){

    var animation = wx.createAnimation({
      delay: 0,
      duration:1000,
      timingFunction:'ease',
    })


    animation.height(0).opacity(0).step()


    this.setData({
      
      zhezhaoHidden:'1',
      seacher_ani:animation.export()
    })

  },
  //整理搜索字符串
  onSearchListData:function(e){

    var str = e.detail.value
    var bodanList = JSON.parse(wx.getStorageSync(JSON.parse(wx.getStorageSync('uid')).uid))
    var programs = bodanList.programs
    var newPrograms = []

    this.setData({
      zhezhaoHidden:"",
    })

    var animation = wx.createAnimation({
      delay: 0,
      duration:1000,
      timingFunction:'ease',
    })

    if(str == ''){

      animation.opacity(0).height(30).step()

      this.setData({

        seacher_list_data:{programs:[{name:'未搜索到相关歌曲'}]},
        seacher_ani:animation.export(),
        zhezhaoHidden:"1",
      })

      return
    }

    for(var i = 0 ; i < programs.length ; i++){

      var name = programs[i].name
      if(name.indexOf(str) !== -1){
        newPrograms.push(programs[i])
      }

    }

    animation.opacity(1).height(newPrograms.length * 30 + 60).step()

    if(newPrograms.length == 0){

      this.setData({

        seacher_list_data:{programs:[{name:'未搜索到相关歌曲'}]},
        seacher_ani:animation.export()
      })

    }else{

      this.setData({

        seacher_list_data:{programs:newPrograms},
        seacher_ani:animation.export()
      })

    }


  },
  // 显示动态列表
  showListBoDan:function(){


    var animation = globalData.showListBoDan('show').export()

    this.setData({
     ani: animation,
     zhezhaoHidden:'',
     playListStatus:wx.getStorageSync('playListStatus')
    })

    var dongTaiLieBiao = globalData.getDongTaiLieBiao()

    var nowMusicId = JSON.parse(wx.getStorageSync('nowMusicId'))

     this.setData({
       bodanList:dongTaiLieBiao.bodanList,
       lishiJiLu:dongTaiLieBiao.lishiJiLu,
       myBodan:dongTaiLieBiao.myBodan,
       nowMusicId:nowMusicId,
     })

   
 },
  onPlayListStatus:function(){
    var playListStatus = globalData.onPlayListStatus()
    this.setData({playListStatus:playListStatus})
  },
  // 隐藏动态列表
  hiddenBoDan:function(){

    var animation = wx.createAnimation({
      duration: 500,
      timingFunction: 'ease',
      delay: 0
    });
    animation.top('100%').step()
    this.setData({
      ani: animation.export(),
      zhezhaoHidden:'1'
    })

  },
  //通过动态列表播放音乐
  DongTaiPlay:function(e){

    this.setData( globalData.DongTaiPlay(e))

  },
  swiperChange_list:function(e){

    var current = e.detail.current

    // console.log(current)

    this.setData({
      activeSwiperChange_list:current
    })

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    var self  = this;

     wx.getStorage({

       key: 'uid',

       success(res){

          var data = JSON.parse(res.data)

          self.setData({uid:data.uid,tabid:data.tabid,nowTitle:data.name})

          if(data.uid.indexOf('bd') == -1){

            wx.getStorage({

              key: data.uid,
              success:function(res){

                
                var programs = JSON.parse(res.data).programs

                // console.log('success=>',programs)
                self.setData({
                  programs:programs,
                  loading:0,
                  
                })

              },
              fail:function(res){

                self.getDbList(data.tabid,data.uid,10000,0,function(res){

                  // console.log(res)
      
                  self.setData({
      
                    programs:res.data.programs,
                    loading:0
                  
                })

                wx.setStorage({
                  data: JSON.stringify(res.data),
                  key: data.uid,
                })
      
                })
              }
            })

          }else{

            wx.getStorage({


              key: data.uid,
              success:function(res){

                var programs = JSON.parse(res.data).programs

                // console.log('success=>',programs)

                for( var i = 0; i< programs.length ; i++){

                  programs[i]['serialNum'] = i+1
                }
                
                self.setData({
                  programs:programs,
                  loading:0,
                  
                })

              },
              fail:function(){
                self.setData({
                  programs:[],
                  loading:0,
                  
                })
              }
            })



          }


       }   
     })

     var nowMu = wx.getStorageSync('nowMusicId')
     
     if(nowMu !==''){

        var nowM = JSON.parse(nowMu)
        this.setData({
          nowMusicId:nowM
        })
     }
    
     
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
    var self =  this
   
    //判断当前播放状态修改播放器的样式
    var nowMu = wx.getStorageSync('nowMusicId')

    if(nowMu !==''){

      this.setData({
        nowMusicId:JSON.parse(nowMu)
      })

      bgMusic.onPlay(function(){
        var nowMusicId = JSON.parse(wx.getStorageSync('nowMusicId'))
        self.setData({
          nowMusicId:nowMusicId
        })
      })

    }

    globalData.onPlay(function(){


      var nowMusicId = wx.getStorageSync('nowMusicId')

      var nowObj = JSON.parse(nowMusicId)

      self.setData({
        nowMusicId:nowObj
      })




    })

    globalData.onPause(function(){
      

      var nowMusicId = wx.getStorageSync('nowMusicId')

      var nowObj = JSON.parse(nowMusicId)

      self.setData({
        nowMusicId:nowObj
      })


    })
    
    var dongTaiLieBiao = globalData.getDongTaiLieBiao()


    this.setData({
      bodanList:dongTaiLieBiao.bodanList,
      lishiJiLu:dongTaiLieBiao.lishiJiLu,
      myBodan:dongTaiLieBiao.myBodan,
    })


    var mybodan = wx.getStorageSync('myBoDan')

      if(mybodan !== ''){

        var data = JSON.parse(mybodan).data

        this.setData({
          bodanNames:data
        })

      }


  },
  toplay:function(e){

    var uid = JSON.parse(wx.getStorageSync('uid'))

    //判断诗歌本是否有音频没有的话就不让进到play的页面
    if(uid.tabid == 1 && e.currentTarget.dataset.bz == undefined){

      wx.showToast({
          
        title: '当前歌曲暂无音频',
        icon:'none',
      })


      return
    }

    


    wx.navigateTo({
      url: '../play/play',
    })

    var nowMusicId = wx.getStorageSync('nowMusicId')

    var id = e.currentTarget.dataset.id

    var name =  e.currentTarget.dataset.name

    

    if(nowMusicId !==''){

      //判断当前进放的play页面是否和正在播放的页面是同一首歌曲
      var nowMusicIdObj =JSON.parse(nowMusicId)

      if(nowMusicIdObj.id == id){

        return
      }

    }

    
    var nowM = JSON.stringify({id:id,status:0,name:name,uid:uid.uid,tabid:uid.tabid,boDanIs:false,boDanUid:uid.uid})

    // console.log('uid.uid=>',uid.uid)

    // console.log('uid.tabid=>',uid.tabid)

    if(uid.tabid == 3){

      var oldUid =  uid.uid

      var arr =  JSON.parse(wx.getStorageSync(uid.uid)).programs

      for( var i = 0 ; i < arr.length ; i++){


        if(arr[i].id == id){

          var tabid = arr[i].tabid

          var uid = arr[i].uid

          break;
        }

      }

      var nowM = JSON.stringify({id:id,status:0,name:name,uid:uid,tabid:tabid,boDanUid:oldUid,boDanIs:true})


    }


    wx.setStorage({
      data: nowM,
      key: 'nowMusicId',
    })

  },
  botToplay:function(){

    var nowMusicId = wx.getStorageSync('nowMusicId')

    if(nowMusicId == ''){
      return;
    }

    wx.navigateTo({
      url: '../play/play',
    })

  },
  getDbList:function(type,id,limit,nowPage,callfun){  //获取数据库内的赞美列表目录

    var self = this

    switch(type){

      case 0:

        wx.request({
            
          url:'https://api.imjad.cn/cloudmusic/',
          data:{type:'djradio',id:id,limit:limit,offset:nowPage * limit,raw:true},
          method:'GET',
          success(res){

           callfun(res)

          }
        })

      break;
      
      case 1:

        wx.cloud.callFunction({
          name:'getDbList',
          data:{
            id:id,
            limit:limit,
            nowPage:nowPage,
          },
          complete:function(res){

          
            res = {data:{programs:res.result.newData,count:res.result.count.total,code:200,more:true}} //与网易云音乐接口同行
            callfun(res)

          }
        })

      break;

      case 2:

        wx.cloud.callFunction({
          name:'getDbXingxi',
          data:{

            id:id,
            limit:limit,
            nowPage:nowPage,
          },
          complete:function(res){

          
            res = {data:{programs:res.result.newData,count:res.result.count.total,code:200,more:true}} //与网易云音乐接口同行
            callfun(res)

          }
        })

      break;

    
    }
    
  },
  onShuaxin:function(e){

    var self = this;
    wx.removeStorage({
      key: self.data.uid,
      loading:1,
    })

    self.getDbList(self.data.tabid,self.data.uid,10000,0,function(res){


      self.setData({

        programs:res.data.programs,
        triggered:false,
       
     })

      wx.setStorage({
        data: JSON.stringify(res.data),
        key: self.data.uid,
      })

    })

  },
  // 跳转到上一个页面
  tonext:function(e){
    wx.navigateBack({
      delta: 0,
    })
  },
  //往播单中添加歌曲
  addBoDan:function(e){


    var bodanNames = this.data.bodanNames

    if(bodanNames[0].name == "请在【我的播单】中创建好播单在添加"){


      return
    }

  
    var id  = e.currentTarget.dataset.id
    var name = e.currentTarget.dataset.name
    var tabid = JSON.parse(wx.getStorageSync('uid')).tabid
    var addBoDanNewInfo = e.currentTarget.dataset
    addBoDanNewInfo['tabid'] = tabid

    this.setData({
      addBoDanInfo:addBoDanNewInfo
    })

 
  },
 
  // //获取当前播放信息【音频链接、图片等信息】
  // getNowMusicInfo:function(fun){

  //   var self = this;

  //   if(wx.getStorageSync('nowMusicId') == ''){
  //     fun({musicUrl:0,})
  //     return
  //   }

  //   var nowMusicId = JSON.parse(wx.getStorageSync('nowMusicId'))

  //   var list = JSON.parse(wx.getStorageSync(nowMusicId.uid)).programs

  //   var tabId = nowMusicId.tabid

  //   var id = nowMusicId.id

  //   var title =nowMusicId.name

  //   for(var i = 0 ; i < list.length ; i++){

  //      if(list[i].id == nowMusicId.id){

  //       switch(tabId){

  //         case 0:

  //           wx.request({
                
  //             url:'https://api.imjad.cn/cloudmusic/',
  //             data:{type:'dj',id:id},
  //             method:'GET',
  //             success(res){
                
  //               var musicUrl = res.data.data[0].url

  //               var coverUrl = list[i].coverUrl


  //               fun({musicUrl:musicUrl,coverUrl:coverUrl,title:title})
    
  //             }
    
  //           })
          
  //         break;
  //         case 1:

  //           var sing = globalData.randomString(32)

  //           var timestamp = new Date().getTime()

           

  //           var musicUrl = 'https://6a69-jiangli-u21is-1302255938.tcb.qcloud.la/' + id + '.mp3?sign=' + sing + '&t=' + timestamp

  //           var coverUrl = 'https://6a69-jiangli-u21is-1302255938.tcb.qcloud.la/' + id + '.jpg?sign=' + sing + '&t=' +timestamp


  //           fun({musicUrl:musicUrl,coverUrl:coverUrl,title:title})

  //         break;

  //         case 2:

  //           // console.log('这是要获取诗信息音频信息')

  //           var sing = globalData.randomString(32)

  //           var timestamp = new Date().getTime()

  //           var musicUrl = 'https://7a68-zhaohuaishuai-9bmq3-1301260178.tcb.qcloud.la/' + id + '.mp3?sign=' + sing + '&t=' + timestamp

  //           var coverUrl = 'https://7a68-zhaohuaishuai-9bmq3-1301260178.tcb.qcloud.la/' + id + '.jpg?sign=' + sing + '&t=' +timestamp

  //           fun({musicUrl:musicUrl,coverUrl:coverUrl,title:title})

  //         break;
  //       }


  //       break;
  //      }
  //   }

  // },
  //显示歌谱
  gepuHidde:function(e){

    globalData.gepuHidde(e)
    
  },

  /*设置列表播放按钮 */
  playIconSet:function(e){

    var self = this

    var id = e.currentTarget.dataset.id

    var name = e.currentTarget.dataset.name

    var nowMu = wx.getStorageSync('nowMusicId')

    var uid =JSON.parse(wx.getStorageSync('uid'))

    if(nowMu == ''){

      var objStatus = {id:id,status:1,name:name,uid:uid.uid,tabid:uid.tabid}

      this.setData({nowMusicId:objStatus})

      var nowM = JSON.stringify(objStatus)

      wx.setStorage({
        data: nowM,
        key: 'nowMusicId',
      })

    }else{

      var nowMuObj = JSON.parse(nowMu)
      
      if(id == nowMuObj.id){


        if(nowMuObj.status == 1 ){

          var objStatus = {id:id,status:0,name:name,uid:uid.uid,tabid:uid.tabid}

          this.setData({nowMusicId:objStatus})

          var nowM = JSON.stringify(objStatus)

          wx.setStorage({
            data: nowM,
            key: 'nowMusicId',
          })



        }else{

          var objStatus = {id:id,status:1,name:name,uid:uid.uid,tabid:uid.tabid}

          this.setData({nowMusicId:objStatus})

          var nowM = JSON.stringify(objStatus)

          wx.setStorage({
            data: nowM,
            key: 'nowMusicId',
          })

          


        }



      }else{

        var objStatus = {id:id,status:1,name:name,uid:uid.uid,tabid:uid.tabid}

        this.setData({nowMusicId:objStatus})

        var nowM = JSON.stringify(objStatus)

        wx.setStorage({
          data: nowM,
          key: 'nowMusicId',
        })

      }
      
    }

    globalData.lishiMusic()

    //判断是否播放
    if(JSON.parse(wx.getStorageSync('nowMusicId')).status == 1){
      globalData.playURLIsOrNo()
    }else{
      bgMusic.pause()
    }

  },
  //  设置底部播放按钮
  botPlayIconSet:function (params) {

    var nowMu = wx.getStorageSync('nowMusicId')

    if(nowMu == ''){

      wx.showToast({
        title: '当前无播放歌曲',
      })

    }else{


      var nowMuObj = JSON.parse(nowMu)  

      var statur = nowMuObj.status == 1?0:1

      if(statur == 1){

        globalData.playURLIsOrNo()

      }else{


        bgMusic.pause()


      }

      var data = {id:nowMuObj.id,status:statur,name:nowMuObj.name,uid:nowMuObj.uid,tabid:nowMuObj.tabid}

 
      this.setData({
        nowMusicId:data
      })

      var data = JSON.stringify({id:nowMuObj.id,status:statur,name:nowMuObj.name,uid:nowMuObj.uid,tabid:nowMuObj.tabid})


      wx.setStorage({
        data: data,
        key: 'nowMusicId',
      })

    }

  },
  onPickerBoDanNameSelect:function(e){


    var bodanNames =  this.data.bodanNames

    var index = e.detail.value

    var uid = bodanNames[index].id

    var bdArr = wx.getStorageSync(uid)

    var id = this.data.addBoDanInfo.id

    var name = this.data.addBoDanInfo.name

    if(bdArr == ''){

      var uidObj = JSON.parse(wx.getStorageSync('uid'))

      uidObj['id'] = id

      uidObj['name'] = name

      var data = {programs:[uidObj]}

      wx.setStorageSync(uid, JSON.stringify(data))

      wx.showToast({

        title: '添加成功',
   
        icon:'none',
   
        duration: 2000//持续的时间
   
      })




    }else{


      var oldBoDan = JSON.parse(bdArr).programs

        for(var i =0 ; i < oldBoDan.length ; i++){

          if(oldBoDan[i].id == id){

            wx.showToast({

              title: '当前歌曲已经在播放列表中',
         
              icon:'none',
         
              duration: 2000//持续的时间
         
            })

            return
           
          }
        }

        var uidObj = JSON.parse(wx.getStorageSync('uid'))

        uidObj['id'] = id

        uidObj['name'] = name

        oldBoDan.push(uidObj)

        var oldBoDanStr = JSON.stringify({programs:oldBoDan})

        wx.setStorageSync(uid, oldBoDanStr)

        wx.showToast({

          title: '添加成功',
     
          icon:'none',
     
          duration: 2000//持续的时间
     
        })





    }


  }
  

})